﻿using System.Collections.Generic;
using System.Linq;
using System.Xml;
using KPIS.GERP.HtmlHelpers;
using KPIS.GERP.Models.SYS.ViewModel;
using KPIS.GERP.WEB.GFMS.Class;

namespace KPIS.GERP.WEB.GFMS.Class
{
    public static class SiteMenuUtility
    {
        private static IEnumerable<MenuItem> MenuItems { get; set; }

        public static IEnumerable<MenuItem> GetMenu()
        {
            if (GimsConfigReader.CacheMenuInMemory)
            {
                return MenuItems ?? LoadAppDataSiteMenuXml();
            }
            else
            {
                return LoadAppDataSiteMenuXml();
            }
        }

        public static IEnumerable<MenuItem> LoadAppDataSiteMenuXml()
        {
            var result = new List<MenuItem>();
            var doc = Models.Class.XmlUtility.LoadXml(MvcUrlHelper.MapPath(GimsConfigReader.SiteMenuXml));

            var stLevelNodes = doc.SelectNodes("MenuItems/MenuItem");

            if (stLevelNodes == null) return result;

            // Loop on 1st level menu
            foreach (XmlNode stLevelNode in stLevelNodes)
            {
                var menu = FetchMenuItemDataFromXmlNode(stLevelNode);
                if (menu == null) continue;
                var ndLevelNodes = stLevelNode.SelectNodes("MenuItem");
                if (ndLevelNodes != null)
                {
                    foreach (XmlNode ndLevelNode in ndLevelNodes)
                    {
                        var submenu = FetchMenuItemDataFromXmlNode(ndLevelNode);
                        if (submenu == null) continue;
                        if (menu.MenuItems == null)
                            menu.MenuItems = new List<MenuItem>();

                        menu.MenuItems.Add(submenu);
                    }
                }
                result.Add(menu);
            }

            MenuItems = result.OrderByDescending(o => o.Sequence);
            return MenuItems;
        }

        private static MenuItem FetchMenuItemDataFromXmlNode(XmlNode xmlNode)
        {
            var result = new MenuItem
            {
                Text = Models.Class.XmlUtility.FetchAttributeValue(xmlNode, "Text"),
                NavigateUrl = Models.Class.XmlUtility.FetchAttributeValue(xmlNode, "NavigateUrl"),
                Icon = Models.Class.XmlUtility.FetchAttributeValue(xmlNode, "Icon"),
                Roles = Models.Class.XmlUtility.FetchAttributeValue(xmlNode, "Roles"),
                AttachAfterHostName = Models.Class.ConvertUtility.ConvertOrDefaultStringToBool(Models.Class.XmlUtility.FetchAttributeValue(xmlNode, "AttachAfterHostName")),
                Sequence = Models.Class.ConvertUtility.ConvertOrDefaultStringToInt(Models.Class.XmlUtility.FetchAttributeValue(xmlNode, "Sequence"))
            };

            return result;
        }

    }
}